package com.tutorial.bf.processor;

import com.tutorial.bf.utils.BaseClassScanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.RootBeanDefinition;

import java.util.Map;

/**
 * @ClassName MyComponentBeanFactoryPostProcessor
 * @Description
 * @Author G
 * @Date 2025/3/11 15:35
 */
public class MyComponentBeanFactoryPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        // 通过扫描工具去扫描指定包及其子包下的所有类，收集使用@MyComponent的注解的类
        Map<String, Class> stringClassMap = BaseClassScanUtils.scanMyComponentAnnotation("com.tutorial.bf.*");
        // 遍历Map，组装BeanDefinition进行注册
        stringClassMap.forEach((beanName, clazz) -> {
            // 获取beanClassName
            String beanClassName = clazz.getName();
            // 创建BeanDefinition
            RootBeanDefinition beanDefinition = new RootBeanDefinition(clazz);
            beanDefinition.setBeanClassName(beanClassName);
            // 注册
            registry.registerBeanDefinition(beanName, beanDefinition);
        });
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
